package pl.edu.utp.calculations;

import java.util.ArrayList;

import pl.edu.utp.ga.Individual;
import pl.edu.utp.ga.genotypes.BinaryGenotype;
import pl.edu.utp.ga.genotypes.NumberGenotype;
import pl.edu.utp.ga.interfaces.Gene;

public class RangeCheck {
		
	private ArrayList<Range> ranges;
	private Individual individual;
	
	public RangeCheck(ArrayList<Range> ranges, Individual individual){
		this.ranges = ranges;
		this.individual = individual;
	}
	
	@SuppressWarnings("unchecked")
	public boolean isInRange(){
		
		if(individual.getGenotype() instanceof NumberGenotype){
			ArrayList<Gene<?>> genes = (ArrayList<Gene<?>>)individual.getGenotype().getGenes();
			for(int i=0;i<genes.size();i++){
				double gene = (Double)genes.get(i).get();
				if(!isValueInRange(gene, i))
					return false;
			}
		
		} else if(individual.getGenotype() instanceof BinaryGenotype){
			BinaryGenotype genotype = (BinaryGenotype)individual.getGenotype();
			for(int i=0;i<(genotype.getGenes().size()/Double.SIZE);i++){
				double value = genotype.getDoubleRepresentation(i);
				if(!isValueInRange(value, i))
					return false;
			}	
		}
		return true;
	}
	
	public boolean isValueInRange(double value, int index){
		try{
			Range range = ranges.get(index);
			if(range.getFrom() > value || value > range.getTo()) {
				return false;
			}
		} catch(ArrayIndexOutOfBoundsException ex){
			return true;
		}
		return true;
	}
}
